/**
 * 通用js方法封装处理
 * Copyright (c) 2020 shoukaiseki
 */
// 当前table相关信息
var sksCache = {
    dataMap: {},
    // 设置实例配置
    set: function (id, value) {
        sksCache.dataMap[id] = value
    },
    // 获取实例配置
    get: function (id) {
        return sksCache.dataMap[id];
    },
};


(function ($) {
    $.extend({
        sksCacheData: {
            set: function (id, value) {
                sksCache.set(id, value)
            },
            // 获取实例配置
            get: function (id) {
                return sksCache.get(id)
            },
        },
        ajaxEasy: function (options) {
            var statusReturn = true;
            var defaults = {
                //获取token的接口名称
                url: "#",
                data: {},
                type: "post",
                dataType: "json",
                async: false,
            };


            var config = $.extend(defaults, options);
            config = $.extend(config, {
                beforeSend: function () {
                    if($.modal&&$.modal.loading){
                        if ($.modal&&$.modal.loading && typeof $.modal.loading === "function") {
                            $.modal.loading("正在处理中，请稍后...");
                        }
                    }
                },
                success: function (result) {
                    console.log("ajaxEasyaa")
                    if ($.modal&&$.modal.closeLoading && typeof $.modal.closeLoading === "function") {
                        $.modal.closeLoading();
                    }
                    if (result.code && result.code == 500) {
                        statusReturn = false
                        if ($.modal&&$.modal.alertError && typeof $.modal.alertError === "function") {
                            $.modal.alertError(result.msg);
                        }
                    }
                    if (options.successCallBack && typeof options.successCallBack === "function") {
                        options.successCallBack(result)
                    }
                }
            });

            $.ajax(config)
            return statusReturn;

        },
        // 确认窗体
        sksModal: {
            /**
             * 暂时该方法未实现，不可用
             * 按确定返回true，并且执行callback
             * @param content
             * @param callBack
             */
            confirmHasRerutn: function (content, callBack) {

                var status = false;

                layer.confirm(
                    content, {title: "提示", icon: 3, btn: ['确认', '取消'], resize: false},
                    function (index) {//确定回调
                        status = true;
                        console.log("layer.confirm.ok")
                        layer.close(index);
                    }, function (index) {//cancel回调
                        status = false;
                        console.log("layer.confirm.cancel")
                        layer.close(index);
                    }
                )


                return status
            }
        },
        //虚拟的xhr，用于其它框架读取进度
        aliyunxhr: {
            defaults: {
                upload: {
                    listenerMap: {},
                    addEventListener: function (eventname, func, b) {
                        var self = this;
                        if (self.listenerMap) {
                            if (self.listenerMap[eventname]) {
                                self.listenerMap[eventname].push(func)
                            } else {
                                var funcs = []
                                funcs.push(func)
                                self.listenerMap[eventname] = funcs;
                            }
                        } else {
                            throw "listenerMap is null"
                        }
                        console.log("addEventListener.listenerMap", self.listenerMap)

                    },
                    eventAction: async function (eventname, even) {
                        var self = this;
                        console.log("aliyunxhr.upload.event")
                        console.log("listenerMap", self.listenerMap)
                        if (self.listenerMap[eventname]) {
                            $.each(self.listenerMap[eventname], function (index, func) {
                                console.log("aliyunxhr.upload.eventname" + eventname)
                                console.log("aliyunxhr.upload.event.value", func)
                                func(even)

                            })
                        }
                    }
                }
            },
            init: function () {
                var obj = {}
                //深拷贝
                obj = $.extend(true, obj, $.aliyunxhr.defaults);
                return obj;
            }

        },
        aliyun: {

            // 判断字符串是否为空
            isEmpty: function (value) {
                if (value == null || this.trim(value) == "") {
                    return true;
                }
                return false;
            },
            trim: function (value) {
                if (value == null) {
                    return "";
                }
                return value.toString().replace(/(^\s*)|(\s*$)|\r|\n/g, "");
            },
            uploadToOss: function (options) {

                var file = options.file


                var fileSize = file.size


                var xhr = undefined;

                // 模拟ajax的 xhr
                xhr = options.ajaxOptions.xhr()


                var params = {
                    fileName: file.name,
                }
                if (options.ownerId) {
                    params.ownerId = options.ownerId
                }

                var defaults = {
                    //获取token的接口名称
                    url: "#",
                    data: params,
                    file: options.file,
                    type: "post",
                    dataType: "json",
                    async: false,
                    beforeSend: function () {
                        $.modal.loading("正在处理中，请稍后...");
                    },
                    success: function (result) {
                        console.log("uploadToOss.1", result)
                        if (result.code && result.code == 500) {
                            $.modal.alertError(result.msg);
                        } else {
                            var stsInfo = $.extend(true, {}, result.data)


                            // 模拟ajax请求，执行ajax的 beforeSend 方法
                            //https://api.jquery.com/Ajax_Events/
                            if (options.ajaxOptions && options.ajaxOptions.beforeSend) {
                                options.ajaxOptions.beforeSend()
                            }


                            var ossClient = new OSS({
                                // withCredentials:true,
                                accessKeyId: stsInfo.accessKeyId,
                                accessKeySecret: stsInfo.accessKeySecret,
                                stsToken: stsInfo.stsToken,
                                // endpoint: 'oss-cn-hangzhou.aliyuncs.com',
                                endpoint: stsInfo.endpoint,
                                bucket: stsInfo.bucket,
                                // region: "oss-cn-hangzhou",
                            });

                            var option = {
                                headers: {
                                    CacheControl: "public",
                                    Expires: '',
                                    ContentEncoding: '',
                                    ContentDisposition: '',
                                    // oss 支持的 header, 目前仅支持 x-oss-server-side-encryption
                                    ServerSideEncryption: '',
                                }
                            }

                            console.log("uploadToOss.file=", file)

                            /**
                             {
                                "Version": "1",
                                "Statement": [
                                    {
                                        "Effect": "Allow",
                                        "Action": [
                                            "oss:ListObjects",
                                            "oss:PutObject",
                                            "oss:GetObject"
                                        ],
                                        "Resource": [
                                            "acs:oss:*:*:test-001a", //test-001a : bucket 名称
                                            "acs:oss:*:*:test-001a/*"
                                        ]
                                    }
                                ]
                            }
                             */


                                // 授权策略是 访问的test目录，如果是其它路径则无法访问
                                // https://help.aliyun.com/document_detail/100624.html?spm=5176.10695662.1996646101.searchclickresult.66576e1e7j9Bk7
                            var storeAs = stsInfo.fileName
                            ossClient.multipartUpload(storeAs, file, {
                                // parallel: 100,
                                // partSize: 1024 * 1024,

                                //cpt:checkpoint
                                //res initResult.res
                                progress: function (p, cpt, res) {
                                    if (options.ajaxOptions && options.ajaxOptions.xhr) {
                                        console.log("options.ajaxOptions.xhr", xhr)
                                        console.log("options.ajaxOptions.xhr.upload", xhr.upload)
                                        console.log("options.ajaxOptions.xhr.eventAction", xhr.upload.eventAction)


                                        console.log("file=", options.file)

                                        var even = {
                                            //文件大小
                                            total: fileSize,
                                            //文件大小
                                            loaded: 0,
                                            // undefined
                                            position: undefined,
                                            // true
                                            lengthComputable: true,
                                        }

                                        // even.loaded = fileSize;
                                        even.loaded = p * fileSize;

                                        xhr.upload.eventAction("progress", even)

                                    }
                                    console.log("进度")
                                    console.log("aliyun.progress.p", p);
                                    console.log("aliyun.progress.cpt", cpt);
                                    console.log("aliyun.progress.res", res);
                                }
                            }).then(function (result) {
                                console.log("aliyun.uploadToOss", result)
                                console.log("options.ajaxOptions", options.ajaxOptions)


                                var ajaxSuccessData = {
                                    wbDocmentId: stsInfo.wbDocmentId,
                                };

                                if (result.res && result.res.requestUrls) {
                                    if (result.res.requestUrls.length == 1) {
                                        ajaxSuccessData.url = result.res.requestUrls[0]
                                    } else {
                                        // ajaxSuccessData.url=stsInfo.url
                                    }
                                } else {
                                    // ajaxSuccessData.url=stsInfo.url
                                }
                                if (options.ajaxOptions) {
                                    if (options.ajaxOptions.success) {
                                        options.ajaxOptions.success(ajaxSuccessData)
                                    }
                                    if (options.ajaxOptions.complete) {
                                        options.ajaxOptions.complete()
                                    }
                                }
                                if (options.fileuploaded && typeof options.fileuploaded === 'function') {
                                    options.fileuploaded(result, stsInfo)
                                } else {

                                }
                            }).catch(function (err) {
                                console.log(err);
                                if (options.ajaxOptions) {
                                    if (options.ajaxOptions.complete) {
                                        options.ajaxOptions.complete()
                                    }
                                }
                            });

                            $.modal.closeLoading();
                        }
                        ;
                    }
                }

                var config = $.extend(defaults, options);
                console.info("aliyun.uploadToOss.config=", config)

                $.ajax(config)
                console.log("xhr", xhr)
                return xhr
            }
        }
    });
})(jQuery);
